package com.wk.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;

import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Expand;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;

public class ZipUtil {

    public static OutputStream zip(String inputFileName, String zipFileName)
            throws Exception

    {
        return zip(zipFileName, new File(inputFileName));

    }

    private static OutputStream zip(String zipFileName, File inputFile)
            throws Exception

    {

        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(

        zipFileName));

        out.setEncoding("UTF-8");// 解决linux乱码 根据linux系统的实际编码设置,可以使用命令
        zip(out, inputFile, "");

        out.close();

        return out;

    }

    private static void zip(ZipOutputStream out, File f, String base)
            throws Exception

    {

        if (f.isDirectory())

        { // 判断是否为目录

            File[] fl = f.listFiles();

            // out.putNextEntry(new org.apache.tools.zip.ZipEntry(base + "/"));

            // out.putNextEntry(new ZipEntry(base + "/"));

            ZipEntry zipEntry = new ZipEntry(base
                    + System.getProperties().getProperty("file.separator"));

            zipEntry.setUnixMode(755);// 解决linux乱码

            out.putNextEntry(zipEntry);

            // base = base.length() == 0 ? "" : base + "/";

            base = base.length() == 0 ? "" : base
                    + System.getProperties().getProperty("file.separator");

            for (int i = 0; i < fl.length; i++)

            {
            	if(fl[i].isFile() && !"11".equals(fl[i].getName()) && !"11.zip".equals(fl[i].getName())){
            		zip(out, fl[i], base + fl[i].getName());
            	}
            }

        }

        else

        { // 压缩目录中的所有文件

            // out.putNextEntry(new org.apache.tools.zip.ZipEntry(base));

            ZipEntry zipEntry = new ZipEntry(base);

            zipEntry.setUnixMode(644);// 解决linux乱码

            out.putNextEntry(zipEntry);

            FileInputStream in = new FileInputStream(f);

            int b;

            while ((b = in.read()) != -1)

            {

                out.write(b);

            }

            in.close();

        }

    }

    public static void unzip(String sourceZip, String destDir)
            throws Exception {

        try {

            Project p = new Project();

            Expand e = new Expand();

            e.setProject(p);

            e.setSrc(new File(sourceZip));

            e.setOverwrite(false);

            e.setDest(new File(destDir));

            e.setEncoding("gbk"); // 根据linux系统的实际编码设置

            e.execute();

        }
        catch (Exception e) {

            throw e;

        }

    }

}
